package com.efeichong.common.utils.json;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;

/**
 * @author lxk
 * @date 2022/8/12
 * @description
 */
public class JsonUtils {

    // 定义jackson对象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 将对象转换成json字符串。
     *
     * @param data
     * @return
     */
    @SneakyThrows
    public static String toJson(Object data) {
        String string = MAPPER.writeValueAsString(data);
        return string;
    }

    public static String toString(Object data) {
        return toJson(data);
    }

    /**
     * 将json结果集转化为对象
     *
     * @param json  json数据
     * @param clazz 对象中的object类型
     * @return
     */
    @SneakyThrows
    public static <T> T toObj(String json, Class<T> clazz) {
        T t = MAPPER.readValue(json, clazz);
        return t;
    }

    /**
     * json字符串转map
     *
     * @param json
     * @return
     */
    @SneakyThrows
    public static FluentMap toMap(String json) {
        return MAPPER.readValue(json, FluentMap.class);
    }

    /**
     * json字符串转list
     *
     * @param json
     * @return
     */
    @SneakyThrows
    public static FluentList toList(String json) {
        return MAPPER.readValue(json, FluentList.class);
    }

    /**
     * json字符串转对象集合
     *
     * @param json
     * @param beanType 集合中的对象类型
     * @return
     */
    @SneakyThrows
    public static <T> FluentList<T> toList(String json, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(FluentList.class, beanType);
        FluentList<T> list = MAPPER.readValue(json, javaType);
        return list;
    }

}
